package com.icss.common.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.icss.common.util.ConstatFinalUtil;
import com.icss.common.vo.ApiResponse;
import com.icss.common.vo.ApiResponseEnum;
import com.icss.service.IUsersDbService;
import com.icss.service.impl.UsersDbServiceImpl;
import com.icss.vo.MakeupAdmins;
import com.icss.vo.MakeupAdminsEnum;
import com.icss.vo.MakeupUsers;
import com.icss.vo.MakeupUsersEnum;

/**
 * ~Servlet开发分三步走: 写一个java代码,Servlet 配置web.xml 在浏览器中访问
 * 
 * ~初始化,Service,一个销毁
 * 
 * @author 陈岩
 */
@WebServlet(urlPatterns = "/NoLoginServlet")
public class NoLoginServlet extends BaseServlet
{
	private IUsersDbService usersDbService;
	
	@Override
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
		this.usersDbService = new UsersDbServiceImpl();
	}
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException
	{
		/* 接收参数 */
		String method = request.getParameter("method");
		if ("adminsLogin".equalsIgnoreCase(method))
		{
			/* 打开管理员登陆页面 */
			adminsLogin(request, response);
		} else if ("adminsLoginSubmit".equalsIgnoreCase(method))
		{
			/* 提交管理员登陆 */
			adminsLoginSubmit(request, response);
		}else if ("login".equalsIgnoreCase(method))
		{
			/* 打开用户登陆页面 */
			login(request, response);
		} else if ("loginSubmit".equalsIgnoreCase(method))
		{
			/* 提交用户登陆 */
			loginSubmit(request, response);
		}else if ("register".equalsIgnoreCase(method))
		{
			/* 打开用户注册页面 */
			register(request, response);
		} else if ("registerSubmit".equalsIgnoreCase(method))
		{
			/* 提交用户注册 */
			registerSubmit(request, response);
		}
	}
	
	/**
	 * 注册提交操作
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void registerSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 存储多个结果,Map存储 */
		Map<String, Object> dataMapJava = new HashMap<String, Object>();
		apiResponse.setDataMapJava(dataMapJava);
		
		HttpSession session = request.getSession() ; 
		
		/* 接收参数 */
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String rand = request.getParameter("rand");
		
		/* session中获取验证码 */
		String randSess = (String) session.getAttribute("randSess");
		
		if(this.regexUtil.verifyCode(randSess, rand))
		{
			MakeupUsers users = new MakeupUsers();
			
			users.setEmail(email);
			users.setPass(password);
			
			users.setStatus(MakeupUsersEnum.STATUS_ENABLE.getStatus());
			
			ApiResponse<Object> apiResponseDb = this.usersDbService.saveOneUsersService(users);
			
			/* 设置数据库的保存信息 */
			apiResponse.setCode(apiResponseDb.getCode());
		}else
		{
			/* 验证码不正确 */
			apiResponse.setCode(ApiResponseEnum.INFO_VERIFY_CODE_INCORR.getStatus());
		}
		
		apiResponse.setInfo(
				ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
				Collections.EMPTY_MAP);
		
		request.setAttribute("response", apiResponse.toJSON());
		this.login(request, response);
	}

	/**
	 * 打开注册页面
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void register(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		/* 准备路径 */
		this.path = "/WEB-INF/jsp/head/register.jsp" ; 
		/* 页面跳转 */
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 登陆提交操作
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void loginSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 存储多个结果,Map存储 */
		Map<String, Object> dataMapJava = new HashMap<String, Object>();
		apiResponse.setDataMapJava(dataMapJava);
		
		HttpSession session = request.getSession() ; 
		
		/* 接收参数 */
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String rand = request.getParameter("rand");
		
		/* session中获取验证码 */
		String randSess = (String) session.getAttribute("randSess");
		
		if(this.regexUtil.verifyCode(randSess, rand))
		{
			/* 验证码正确 */
			/* 查询db,处理业务逻辑 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("email", email);
			ApiResponse<MakeupUsers> apiRes = this.usersDbService.findOneUsersService(condMap);
			MakeupUsers users = apiRes.getDataOneJava();
			/* 检验邮箱 */
			if (users != null)
			{
				/* 将邮箱放到request中 */
				dataMapJava.put("email", users.getEmail());
				/* 检验密码 */
				if (this.encryptUtil.checkStr(password, users.getPass()))
				{
					/* 状态必须为启用 */
					if (users.getStatus() == MakeupAdminsEnum.STATUS_ENABLE.getStatus())
					{
						session.setAttribute("users", users);
						session.setAttribute("lastLoginTime", users.getLastLoginTime());
						
						/* 登陆成功 */
						users.setLastLoginTime(new Date());

						this.usersDbService.updateOneUsersService(users);
						
						/* 说明已经登陆 */
						response.sendRedirect(request.getContextPath() + "/head/UsersHeadServlet?method=main");
						return ; 
					} else
					{
						/* 状态为禁用 */
						apiResponse.setCode(ApiResponseEnum.INFO_ACCOUNT_DISABLED.getStatus());
					}
				} else
				{
					apiResponse.setCode(ApiResponseEnum.INFO_PASS_INCORRECT.getStatus());
				}
			}else
			{
				/* 邮箱不存在 */
				apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_NOT_EXISTS.getStatus());
			}
		}else
		{
			/* 验证码不正确 */
			apiResponse.setCode(ApiResponseEnum.INFO_VERIFY_CODE_INCORR.getStatus());
		}
		
		apiResponse.setInfo(
				ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
				Collections.EMPTY_MAP);
		
		this.updateFlag = "true" ; 
		request.setAttribute("response", apiResponse.toJSON());
		this.login(request, response);
	}

	/**
	 * 打开登陆页面
	 * @param request
	 * @param response
	 * @throws IOException
	 * @throws ServletException
	 */
	private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		/* 准备路径 */
		this.path = "/WEB-INF/jsp/head/login.jsp" ; 
		/* 从session获取信息 */
		MakeupUsers users = (MakeupUsers) this.findObjfromSession(request, "users");
		if(users != null)
		{
			/* 说明已经登陆 */
			response.sendRedirect(request.getContextPath() + "/head/UsersHeadServlet?method=main");
			return ; 
		}
		/* 页面跳转 */
		request.getRequestDispatcher(path).forward(request, response);
	}

	/**
	 * 提交管理员登陆
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void adminsLoginSubmit(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 存储多个结果,Map存储 */
		Map<String, Object> dataMapJava = new HashMap<String, Object>();
		apiResponse.setDataMapJava(dataMapJava);
		
		HttpSession session = request.getSession() ; 
		
		/* 接收参数 */
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String rand = request.getParameter("rand");
		
		/* session中获取验证码 */
		String randSess = (String) session.getAttribute("randSess");
		
		if(this.regexUtil.verifyCode(randSess, rand))
		{
			/* 验证码正确 */
			/* 查询db,处理业务逻辑 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("email", email);
			ApiResponse<MakeupAdmins> apiRes = this.usersDbService.findOneAdminsService(condMap);
			MakeupAdmins admins = apiRes.getDataOneJava();
			/* 检验邮箱 */
			if (admins != null)
			{
				/* 将邮箱放到request中 */
				dataMapJava.put("email", admins.getEmail());
				/* 检验密码 */
				if (this.encryptUtil.checkStr(password, admins.getPass()))
				{
					/* 状态必须为启用 */
					if (admins.getStatus() == MakeupAdminsEnum.STATUS_ENABLE.getStatus())
					{
						session.setAttribute("admins", admins);
						session.setAttribute("lastLoginTime", admins.getLastLoginTime());
						
						/* 登陆成功 */
						admins.setLastLoginTime(new Date());

						this.usersDbService.updateOneAdminsService(admins);
						
						/* 说明已经登陆 */
						response.sendRedirect(request.getContextPath() + "/back/AdminsBackServlet?method=main");
						return ; 
					} else
					{
						/* 状态为禁用 */
						apiResponse.setCode(ApiResponseEnum.INFO_ACCOUNT_DISABLED.getStatus());
					}
				} else
				{
					apiResponse.setCode(ApiResponseEnum.INFO_PASS_INCORRECT.getStatus());
				}
			}else
			{
				/* 邮箱不存在 */
				apiResponse.setCode(ApiResponseEnum.INFO_EMAIL_NOT_EXISTS.getStatus());
			}
		}else
		{
			/* 验证码不正确 */
			apiResponse.setCode(ApiResponseEnum.INFO_VERIFY_CODE_INCORR.getStatus());
		}
		
		apiResponse.setInfo(
				ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
				Collections.EMPTY_MAP);
		
		request.setAttribute("response", apiResponse.toJSON());
		this.adminsLogin(request, response);
	}

	/**
	 * 打开管理员登陆页面
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void adminsLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		/* 准备路径 */
		this.path = "/WEB-INF/jsp/back/login.jsp" ; 
		/* 从session获取信息 */
		MakeupAdmins admins = (MakeupAdmins) this.findObjfromSession(request, "admins");
		if(admins != null)
		{
			/* 说明已经登陆 */
			response.sendRedirect(request.getContextPath() + "/back/AdminsBackServlet?method=main");
			return ; 
		}
		/* 页面跳转 */
		request.getRequestDispatcher(path).forward(request, response);
	}
}
